<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Model\SocialAccount;
use App\Model\Spread\SpreadAccount;
use App\Model\Spread\SpreadLog;
use App\Model\User;
use App\Model\UserDevice;
use App\Model\UserProfile;

/**
 * 第三方登录（注册）
 */
class AuthSocialService extends AuthBaseService
{
    protected $socialProvider = [
        1 => 'qq',
        2 => 'weixin',
        3 => 'apple',
    ];

    protected function RoVerifyList()
    {
        return [
            'provider' => "required|string",
            'openid' => "required|string"
        ];
    }

    public function handle()
    {
        $provider = $this->request->input('provider');
        $openId = $this->request->input('openid');
        $cpaCode = $this->request->input('cpa_code','');

        if (!in_array($provider, $this->socialProvider)) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '渠道无效！');
        }

        //苹果账号MD5处理
        if ($provider == 'apple') $openId = md5($openId);

        //是否存在第三方注册账号
        $socialAccount = SocialAccount::check($provider, $openId);

        //返回数组
        $ret = [
            //登录token
            'token' => '',
            //需要完善个人资料
            'fix_profile' => 1,
            //个人资料
            'user_info' => null,
        ];
        //还未注册第三方
        if (!$socialAccount) {
            //注册检测
            $check = $this->checkRegister();
            if ($check['errcode'] > 0) return $this->setError($check['errcode'], $check['errmsg']);

            $user = $this->doRegister();
            if (!$user) {
                return $this->setError(ErrorCode::SERVER_ERROR, '注册账号失败！');
            }
            SocialAccount::createAccount($user->id, $provider, $openId);
        }
        //已注册了第三方账号
        elseif ($socialAccount && $user = $socialAccount->user) {
            //冻结
            if ($user->status == User::STATUS_FREEZE) {
                return $this->setError(ErrorCode::USER_NOT_VALID, '该用户涉嫌违规已被冻结账号！');
            }
            //已注销
            if ($user->status == User::STATUS_CANCELLATTED) {
                return $this->setError(ErrorCode::USER_NOT_VALID, '该用户已经注销账号~');
            }
        }



        //记录设备ID
        if ($deviceId = $this->request->input('cid', '')) {
            UserDevice::addRecord($user->id, $deviceId);
        }

        //用户登录
        $ret['token'] = $this->autoLogin($user);
        $ret['user_info'] = $this->packBaseUserInfo($user);
        //需要完善个人资料
        $ret['fix_profile'] = !isset($ret['user_info']['gender']) ? 1 : 0;

        if (!isset($ret['user_info']['user_profile_id'])) {
            //cpa邀请码
            if (
                $cpaCode &&
                SpreadAccount::getInfoByUserId($cpaId = SpreadAccount::checkUserId($cpaCode))
            ) {
                $upInfo['cpa_code'] = $cpaId;
                SpreadLog::updateOrCreate(['user_id' => $ret['user_info']['user_id']],[
                    's_id' => $cpaId,
                    'is_activate' => 0
                ]);

                UserProfile::updateOrCreate(['user_id' => $ret['user_info']['user_id']], $upInfo);
            }
        }

        //是否有融云账号
        if (!$user->im_account || !$user->im_token || $user->id <= env('RONG_NEW_START_UID', 803)) {
            $name = $ret['user_info']['nick_name'] ?? '';
            $avatar = $ret['user_info']['avatar'] ?? '';
            $ret['im_info']  = User::createRongIMAccount($user->id, $name, $avatar);
        } else {
            $ret['im_info'] = ['im_account' => $user->im_account, 'im_token' => $user->im_token];
        }

        $ret['show_invitecode'] = env('SHOW_INVITECODE', 1);
        log_info(__CLASS__ . "==" . json_encode($ret));
        return $ret;
    }
}
